//
//  SWUserAccountViewModel.swift
//  SinaWeibo
//
//  Created by AenyMo on 16/3/31.
//  Copyright © 2016年 AenyMo. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class SWUserAccountViewModel: NSObject {
    
    //懒加载 userAccount属性
    lazy var userAccount: SWUserAccount? = {
        
        return SWUserAccount.loadAccountFromSanbox()
    }()
    
    //判断用户是否登录
    var userLogin: Bool {
        
        return userAccount?.access_token != nil
    }
    

    //获取token
    class func accessToken(code: String, finished: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //配置post请求参数
        let para = ["client_id": client_id,
                    "client_secret": client_secret,
                    "grant_type": "authorization_code",
                    "code": code,
                    "redirect_uri": redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        //设置响应序列化 类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //发送请求
        AFN.POST(urlString, parameters: para, progress: nil, success: { (_, result) in
            //
            SVProgressHUD.dismiss()
            
            //解析返回结果    如果是一个字典
            if let dict = result as? [String: AnyObject] {
                
                //字典转模型
                let userAccount = SWUserAccount(dict: dict)
                
                //获取用户信息
                accessUserInfo(userAccount, finished: finished)
            }
            
        }) { (_, error) in
            //
            print(error)
        }
    }
    //获取用户信息
    class private func accessUserInfo(userAccount: SWUserAccount, finished: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let para = ["access_token": userAccount.access_token!,
                    "uid": userAccount.uid!]
        
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: para, progress: nil, success: { (_, result) in
            //
            if let dict = result as? [String: AnyObject] {
                
                //给模型属性赋值
                userAccount.avatar_large = dict["avatar_large"] as? String
                userAccount.name = dict["name"] as? String
                
                //保存账户信息到沙盒
                userAccount.saveAccountToSanbox()
                
                finished(error: nil)
            }
            
        }) { (_, error) in
            //
            print(error)
            //回调代码
            finished(error: error)
        }
    }
}
